package com.chagee.store.operation.server.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.alibaba.arms.tracing.Span;
import com.alibaba.arms.tracing.Tracer;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chagee.store.operation.api.enums.OrderAcceptanceTypeEnum;
import com.chagee.store.operation.api.enums.StoreTaskEnum;
import com.chagee.store.operation.api.enums.StoreWorkOrderStatusEnum;
import com.chagee.store.operation.common.constant.CommonConstant;
import com.chagee.store.operation.server.entity.*;
import com.chagee.store.operation.server.event.dao.StoreConfigurationMapper;
import com.chagee.store.operation.server.event.service.TaskExecutionBaseService;
import com.chagee.store.operation.server.event.service.WorkOrderBaseService;
import com.chagee.store.operation.server.event.service.WorkOrderReceiverBaseService;

import com.chagee.store.operation.server.service.WorkOrderAcceptanceService;
import com.chagee.store.operation.server.service.biz.TaskExecutionBizService;
import com.lark.oapi.core.utils.Lists;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 自动提交完成验收
 */
@Component
@Slf4j
public class AutoAcceptanceJobHandler {

	@Resource
	private WorkOrderBaseService workOrderBaseService;
	@Resource
	private TaskExecutionBaseService taskExecutionBaseService;
	@Resource
	private TaskExecutionBizService taskExecutionBizService;
	@Resource
	private WorkOrderReceiverBaseService workOrderReceiverBaseService;
	@Resource
	private StoreConfigurationMapper storeConfigurationMapper;

	@Resource
	private WorkOrderAcceptanceService workOrderAcceptanceService;

	/**
	 * 自动提交完成验收
	 *
	 * @param param
	 * @return
	 */
	@XxlJob("autoAcceptanceHandler")
	public ReturnT<String> autoAcceptanceHandler(String param) {
		Span span = Tracer.builder().getSpan();
		TimeInterval timer = DateUtil.timer();
		log.info("自动提交完成验收定时任务开始,traceId :{}", span.getTraceId());
		try {
			if (StringUtils.isNotBlank(param)) {
				List<String> storeCodeList = Arrays.stream(param.split(",")).map(String::trim).filter(StringUtils::isNotBlank).collect(Collectors.toList());
				workOrderAcceptanceService.acceptance(storeCodeList);
			}else {
				//获取当前时间
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date());
				int hour = calendar.get(Calendar.HOUR_OF_DAY);
				log.info("当前时间:{},自动验收任务!" , hour);
				long startIndex = 0L;
				while (true) {

					//store_configuration 配置自动打烊验收时间 且该门店三方打烊任务状态为启用
					List<StoreConfigurationDO> configurationDOS = storeConfigurationMapper.selectByAutoAcceptanceTime(startIndex,hour + ".00");
					if (CollectionUtils.isEmpty(configurationDOS)) {
						break;
					}
					List<String> storeCodeList = configurationDOS.stream().map(StoreConfigurationDO::getStoreCode).collect(Collectors.toList());
					log.info("查询已配置自动验收时间且开启三方打烊状态门店：" + JSONObject.toJSON(storeCodeList));

					workOrderAcceptanceService.acceptance(storeCodeList);
					startIndex = Math.toIntExact(configurationDOS.stream().map(StoreConfigurationDO::getId).max(Comparator.naturalOrder()).orElse(0L));
				}
			}
		} catch (Exception e) {
			XxlJobLogger.log("自动提交完成验收定时任务异常，异常信息:", e);
			log.error("自动提交完成验收定时任务异常 => param : {} => 异常信息 :", param, e);
		}
		XxlJobLogger.log("自动提交完成验收定时任务结束，共耗时:{},TraceId:{}", timer.intervalRestart(), span.getTraceId());
		return ReturnT.SUCCESS;
	}
}
